<!-- 
  如果传入props.imgs，优先用，没传就用父组件注入的log.imgs
  如果是 用户log 就要有要有查看原图的功能，但是爬虫数据不需要查看原图功能
 -->
<script setup lang="ts">
	import { ref } from "vue";
	import { inject, computed } from 'vue'
	import { toFileUrl } from '@/utils/cos'
	import type { Log } from "@/env.d"

	// 从父组件拿到log，主要是获取userId
	const log : Log = inject('log')!

	/**
	 * imgs是图片列表
	 */
	const props = defineProps<{ imgs ?: string[] }>()
	// 计算从哪里取属性
	const imgs = computed(() => props.imgs || log.imgs)
	// 传入的图片要处理，如果不是http开头，就加上OOS地址
	const imgUrls = ref<string[]>(
		toFileUrl(imgs.value, 'compress-imgs/', log.userid)
	)

	watch(imgs, () => {
		imgUrls.value = toFileUrl(imgs.value, 'compress-imgs/', log.userid)
	})

	const click_img = (url : string) => {
		uni.previewImage({
			current: url,
			urls: imgUrls.value,
			longPressActions: {
				itemList: ['发送给朋友', '保存原图'],
				success: function (data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					// 保存原图
					if (data.tapIndex === 0) {

					} else if (data.tapIndex === 1) {
						uni.saveImageToPhotosAlbum({
							filePath: toFileUrl(imgs.value[data.index], 'imgs/', log.userid),
							success: () => {
								uni.showToast({ title: '保存成功' })
							}
						})
					}
				},
				fail: function (err) {
					console.log(err.errMsg);
				}
			}
		})
	}
</script>

<template>
	<scroll-view scroll-x class="viewer-imgs">
		<view class="imgs">
			<template v-for="i in imgUrls" :key="i">
				<image :src="i" mode="aspectFill" lazy-load @click="click_img(i)" />
			</template>
		</view>
	</scroll-view>
</template>

<style scoped lang="scss">
	.viewer-imgs {
		width: fit-content;
		max-width: 100%;
		
		.imgs {
			display: flex;
			gap: var(--block-gap);
			flex-direction: row;
			flex-wrap: nowrap;

			image {
				flex-shrink: 0;
				border-radius: var(--block-border-radius);
				width: var(--block-height);
				height: var(--block-height);
			}
		}
	}
</style>
